package sy.service.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.jpush.api.utils.BaseCompare;
import cn.jpush.api.utils.Compares;
import sy.dao.ResourceDaoI;
import sy.dao.RoleDaoI;
import sy.dao.UserDaoI;
import sy.model.Taskrecord;
import sy.model.Tinviterecord;
import sy.model.Tresource;
import sy.model.Trole;
import sy.model.Tuser;
import sy.pageModel.DataGrid;
import sy.pageModel.PageHelper;
import sy.pageModel.SessionInfo;
import sy.pageModel.User;
import sy.service.InviteServiceI;
import sy.service.UserServiceI;
import sy.util.DESUtil;
import sy.util.MD5Util;

@Service
public class UserServiceImpl implements UserServiceI {

	@Autowired
	private UserDaoI userDao;

	@Autowired
	private RoleDaoI roleDao;

	@Autowired
	private ResourceDaoI resourceDao;

	@Autowired
	private InviteServiceI inviteDao;
	
 
	public User login(User user) {
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("userid", user.getUserid());
		    //params.put("pwd",MD5Util.md5(user.getPwd())); 
			params.put("pwd",DESUtil.encrypt(user.getPwd())); 
			//System.out.println(user.getPwd());
			//System.out.println(MD5Util.md5(user.getPwd()));
			Tuser t = userDao.get("from Tuser t where t.userid = :userid and t.pwd = :pwd", params);
			if (t != null) {
				BeanUtils.copyProperties(t, user);
				return user;
			}
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return null;
	}

	
	public User loginadmin(User user) {
		Map<String, Object> params=null;
		try {
			params = new HashMap<String, Object>();
			params.put("name", user.getName());
			params.put("pwd",DESUtil.encrypt(user.getPwd()));
		} catch (Exception e) {
			e.printStackTrace();
		} 
		Tuser t = userDao.get("from Tuser t where t.name = :name and t.pwd = :pwd", params);
		if (t != null) {
			BeanUtils.copyProperties(t, user);
			return user;
		}
		return null;
	}
	 
	synchronized public void regonce(User user) throws Exception { 
			Tuser u = new Tuser();
			u.setId(UUID.randomUUID().toString());
			u.setName(user.getName());
			u.setPwd(DESUtil.encrypt(user.getPwd()));
			//u.setPwd(MD5Util.md5(user.getPwd()));
			u.setCreatedatetime(new Date()); 			  //创建时间
			u.setUserid(user.getUserid());				  //用户userid
			u.setChangedscore(0);						  //兑换积分
			u.setChangedcount(0);						  //兑换次数
			u.setUnchangedscore(user.getUnchangedscore());//剩余积分
			u.setTotalscore(user.getTotalscore());		  //总共积分
			u.setScorefrominvite(0);					  //邀请次数积分
			u.setInvitecount(0);						  //邀请次数
			u.setTaskcount(1);							  //任务次数
			u.setLevl(1);								  //等级
			u.setGgjnunber(1);							  //用户注册一次有一次刮奖机会
			u.setStatu("1");							  //初始化审核通过
			userDao.save(u); 
	}

	 
	public DataGrid dataGrid(User user, PageHelper ph) {
		DataGrid dg = new DataGrid();
		List<User> ul = new ArrayList<User>();
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = " from Tuser t ";
		List<Tuser> l = userDao.find(hql + whereHql(user, params) + orderHql(ph), params, ph.getPage(), ph.getRows());
		if (l != null && l.size() > 0) {
			for (Tuser t : l) {
				User u = new User();
				try {
					//u.setUnline(inviteDao.getCount(t.getUserid()+""));
                    //递归查询该用户下线人数
                    if(t.getUserid()!=null){
                        int isDe =  inviteDao.QueryUnlineCount(t.getUserid() + "","start");
                        u.setUnline(isDe+""); 
                    }


				} catch (Exception e) {
					e.printStackTrace();
				}
				BeanUtils.copyProperties(t, u);
				ul.add(u);
			}
		}
		dg.setRows(ul);
		dg.setTotal(userDao.count("select count(*) " + hql + whereHql(user, params), params));
		return dg;
	}

	private String whereHql(User user, Map<String, Object> params) {
		String hql = "";
		if (user != null) {
			hql += " where 1=1 ";
			if (user.getName() != null) {
				hql += " and (t.name like :name or cast(t.userid as string) like :userid)";
				params.put("name", "%%" + user.getName() + "%%");
				params.put("userid", "%%" + user.getName() + "%%");
			}
			if (user.getStatu() != null) {
				if("3".equals(user.getStatu())){
					
				}else{
					hql += " and t.statu = :statu";
					params.put("statu", user.getStatu());
				}
			}
			if (user.getCreatedatetimeStart() != null) {
				hql += " and t.createdatetime >= :createdatetimeStart";
				params.put("createdatetimeStart", user.getCreatedatetimeStart());
			}
			if (user.getCreatedatetimeEnd() != null) {
				hql += " and t.createdatetime <= :createdatetimeEnd";
				params.put("createdatetimeEnd", user.getCreatedatetimeEnd());
			}
			if (user.getModifydatetimeStart() != null) {
				hql += " and t.modifydatetime >= :modifydatetimeStart";
				params.put("modifydatetimeStart", user.getModifydatetimeStart());
			}
			if (user.getModifydatetimeEnd() != null) {
				hql += " and t.modifydatetime <= :modifydatetimeEnd";
				params.put("modifydatetimeEnd", user.getModifydatetimeEnd());
			}
		}
		 
		return hql;
	}

    
    public Tuser getUserByUserId(String userid){

        String hql="from Tuser t where t.userid="+userid;
        List<Tuser> list=userDao.find(hql);

        if(list.size()>0){

           return list.get(0);
        }else{
            return null;
        }
      }
    
    
    public Tuser TusergetUserByNickname(String name){
        String hql="from Tuser t where t.name="+name;
        List<Tuser> list=userDao.find(hql);
        if(list.size()>0){
           return list.get(0);
        }else{
            return null;
        }
      }
    
	private String orderHql(PageHelper ph) {
		String orderString = "";
		if (ph.getSort() != null && ph.getOrder() != null) {
			orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
		}
		return orderString;
	}

	
	synchronized public void add(User user) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("name", user.getName());
		if (userDao.count("select count(*) from Tuser t where t.name = :name", params) > 0) {
			throw new Exception("登录名已存在！");
		} else {
			Tuser u = new Tuser();
			BeanUtils.copyProperties(user, u);
			u.setCreatedatetime(new Date());
			u.setPwd(DESUtil.encrypt(user.getPwd()));
			userDao.save(u);
		}
	}

	
	public User get(String id) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		Tuser t = userDao.get("select distinct t from Tuser t left join fetch t.troles role where t.id = :id", params);
		User u = new User();
		BeanUtils.copyProperties(t, u);
		if (t.getTroles() != null && !t.getTroles().isEmpty()) {
			String roleIds = "";
			String roleNames = "";
			boolean b = false;
			for (Trole role : t.getTroles()) {
				if (b) {
					roleIds += ",";
					roleNames += ",";
				} else {
					b = true;
				}
				roleIds += role.getId();
				roleNames += role.getName();
			}
			u.setRoleIds(roleIds);
			u.setRoleNames(roleNames);
		}
		return u;
	}

	
	synchronized public void edit(User user) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", user.getId());
		params.put("name", user.getName());
		if (userDao.count("select count(*) from Tuser t where t.name = :name and t.id != :id", params) > 0) {
			throw new Exception("登录名已存在！");
		} else {
			Tuser u = userDao.get(Tuser.class, user.getId());
					BeanUtils.copyProperties(user, u, new String[] { "ID","changedcount", 
					"changedscore","createdatetime","invitecount", "levl" , "pwd","taskcount" 
					, "scorefrominvite" ,"totalscore", "unchangedscore", "userid","statu"  });
					u.setModifydatetime(new Date());
		}
	}

	
	public void delete(String id) {
		userDao.delete(userDao.get(Tuser.class, id));
	}

	
	public void grant(String ids, User user) {
		if (ids != null && ids.length() > 0) {
			List<Trole> roles = new ArrayList<Trole>();
			if (user.getRoleIds() != null) {
				for (String roleId : user.getRoleIds().split(",")) {
					roles.add(roleDao.get(Trole.class, roleId));
				}
			}
			for (String id : ids.split(",")) {
				if (id != null && !id.equalsIgnoreCase("")) {
					Tuser t = userDao.get(Tuser.class, id);
					t.setTroles(new HashSet<Trole>(roles));
				}
			}
		}
	}

	
	public List<String> resourceList(String id) {
		List<String> resourceList = new ArrayList<String>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		Tuser t = userDao.get("from Tuser t join fetch t.troles role join fetch role.tresources resource where t.id = :id", params);
		if (t != null) {
			Set<Trole> roles = t.getTroles();
			if (roles != null && !roles.isEmpty()) {
				for (Trole role : roles) {
					Set<Tresource> resources = role.getTresources();
					if (resources != null && !resources.isEmpty()) {
						for (Tresource resource : resources) {
							if (resource != null && resource.getUrl() != null) {
								resourceList.add(resource.getUrl());
							}
						}
					}
				}
			}
		}
		return resourceList;
	}

	
	public void editPwd(User user) {
		if (user != null && user.getPwd() != null && !user.getPwd().trim().equalsIgnoreCase("")) {
			Tuser u = userDao.get(Tuser.class, user.getId());
			try {
				u.setPwd(DESUtil.encrypt(user.getPwd()));
			} catch (Exception e) {
				e.printStackTrace();
			}
			u.setModifydatetime(new Date());
		}
	}

	
	public boolean editCurrentUserPwd(SessionInfo sessionInfo, String oldPwd, String pwd) {
		Tuser u = userDao.get(Tuser.class, sessionInfo.getId());
		try {
			if (u.getPwd().equalsIgnoreCase(DESUtil.encrypt(oldPwd))) {// 说明原密码输入正确
				u.setPwd(DESUtil.encrypt(pwd));
				u.setModifydatetime(new Date());
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			 
		}
		return false;
	}

	
	public List<User> loginCombobox(String q) {
		if (q == null) {
			q = "";
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("name", "%%" + q.trim() + "%%");
		List<Tuser> tl = userDao.find("from Tuser t where t.name like :name order by name", params, 1, 10);
		List<User> ul = new ArrayList<User>();
		if (tl != null && tl.size() > 0) {
			for (Tuser t : tl) {
				User u = new User();
				u.setName(t.getName());
				ul.add(u);
			}
		}
		return ul;
	}

	
	public DataGrid loginCombogrid(String q, PageHelper ph) {
		if (q == null) {
			q = "";
		}
		DataGrid dg = new DataGrid();
		List<User> ul = new ArrayList<User>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("name", "%%" + q.trim() + "%%");
		List<Tuser> tl = userDao.find("from Tuser t where t.name like :name order by " + ph.getSort() + " " + ph.getOrder(), params, ph.getPage(), ph.getRows());
		if (tl != null && tl.size() > 0) {
			for (Tuser t : tl) {
				User u = new User();
				u.setName(t.getName());
				u.setCreatedatetime(t.getCreatedatetime());
				u.setModifydatetime(t.getModifydatetime());
				ul.add(u);
			}
		}
		dg.setRows(ul);
		dg.setTotal(userDao.count("select count(*) from Tuser t where t.name like :name", params));
		return dg;
	}
	
	public List<Long> userCreateDatetimeChart() {
		List<Long> l = new ArrayList<Long>();
		int k = 0;
		for (int i = 0; i < 12; i++) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("s", k);
			params.put("e", k + 2);
			k = k + 2;
			l.add(userDao.count("select count(*) from Tuser t where HOUR(t.createdatetime)>=:s and HOUR(t.createdatetime)<:e", params));
		}
		return l;
	}
	
	public Long regonce() {
		return userDao.count("select count(*) from Tuser t");
	}
	
	public List<User> fealtyrank() {
		List<Tuser> tl = userDao.find(" from Tuser  order by levl desc");
		List<User> ul = new ArrayList<User>();
		int leng = tl.size();
		if(leng<=30){
			leng=tl.size();
		}else{
			leng=30;
		} 
			for(int i = 0;i<leng;i++){
				User u = new User();
				u.setName(tl.get(i).getName()); //昵称
				u.setOrderid(i+1);	   		    //顺序id
				u.setLevl(tl.get(i).getLevl()); //等级
				ul.add(u);
			}
		
		return ul;
	}
	
	
	public List<User> regalrank() {
		List<Tuser> tl = userDao.find(" from Tuser   order by unchangedscore desc");
		List<User> ul = new ArrayList<User>();
		int leng = tl.size();
		if(leng<=30){
			leng=tl.size();
		}else{
			leng=30;
		}  
			for(int i = 0;i<leng;i++){
				User u = new User();
				u.setName(tl.get(i).getName()); //昵称
				u.setOrderid(i+1);	   		    //顺序id
				u.setUnchangedscore(tl.get(i).getUnchangedscore()); //等级
				ul.add(u);
			}
		
		return ul;
	}

	
	public List<User> outstandrank() {
		List<Tuser> tl = userDao.find(" from Tuser s where s.userid in (select m.userid from Tinviterecord m where    DATE_FORMAT(m.registertime,'%U')= DATE_FORMAT(now(),'%U')) ");
		List<Compares> com = new ArrayList<Compares>();
		List<User> comusers = new ArrayList<User>();
		int leng = tl.size();
			if(leng<=30){
				leng=tl.size();
			}else{
				leng=30;
			}  
			User u = null;
			Compares cp = null;
			for(int i = 0;i<leng;i++){
				u  = new User();
				cp = new Compares();
				u.setName(tl.get(i).getName()); 			//昵称
				u.setOrderid(i+1);	   		    			//顺序id
				u.setTotalscore(inviteDao.getTinviterecordWeekCount(tl.get(i).getUserid()+"","start")); //等级
				cp.setCount(inviteDao.getTinviterecordWeekCount(tl.get(i).getUserid()+"","start"));//根据该人查询对应的本周推广人数
				cp.setObj(u);
				com.add(cp);
		}
		Comparator<Compares> ascComparator = new BaseCompare();
		Collections.sort(com, ascComparator);
		Comparator<Compares> descComparator = Collections.reverseOrder(ascComparator);
		Collections.sort(com, descComparator);
		for(Compares c:com){
			comusers.add((User)c.getObj());
		}
		return comusers;

	}
	
	public List<User> weekrank() {
		List<Tuser> tl = userDao.find(" from Tuser   order by totalscore desc");
		List<User> ul = new ArrayList<User>();
			int leng = tl.size();
			if(leng<=30){
				leng=tl.size();
			}else{
				leng = 30;
			} 
			for(int i = 0;i<leng;i++){
				User u = new User();
				u.setName(tl.get(i).getName()); //昵称
				u.setOrderid(i+1);	   		    //顺序id
				u.setTotalscore(tl.get(i).getTotalscore()); //等级
				ul.add(u);
			}
		 
		return ul;
	}

	
	public String getpwd(User user) {
		 Map<String, Object> params = new HashMap<String, Object>();
		 params.put("userid", user.getUserid());
		 params.put("phonenumber", user.getPhonenumber());
		 Tuser t = userDao.get("from Tuser t  where t.userid = :userid and t.phonenumber = :phonenumber", params);
		 if(t == null){
			 return "fail";
		 }else{
			 return DESUtil.decrypt(t.getPwd());
		 }
	}

	
	public void edittaskcount(User user) throws Exception {
		Tuser u = userDao.get(Tuser.class, user.getId());
		BeanUtils.copyProperties(user, u, new String[] { "ID", "alipay","changedcount", "changedscore","createdatetime"
				,"invitecount", "levl" , "name" ,"phonenumber", "pwd" ,"qq", "scorefrominvite" ,"totalscore", "unchangedscore", "userid","statu"  });
		u.setTaskcount(user.getTaskcount());//更新任务记录
		u.setModifydatetime(new Date());	//更新操作时间
	}
 
	
	public void editotlescore(User user) throws Exception {
		Tuser u = userDao.get(Tuser.class, user.getId());
		BeanUtils.copyProperties(user, u, new String[] { "ID", "alipay","changedcount", "changedscore","createdatetime"
				,"invitecount", "levl" , "name" ,"phonenumber", "pwd" ,"qq", "scorefrominvite" , "userid","statu"  });
		u.setTaskcount(user.getTaskcount());			//更新任务记录
		u.setTotalscore(user.getTotalscore());			//更新总积分
		u.setUnchangedscore(user.getUnchangedscore());	//更新可兑换积分
		u.setModifydatetime(new Date());				//更新操作时间
		
	}

	
	public void editexchangescore(User user) throws Exception {
		Tuser u = userDao.get(Tuser.class, user.getId());
		BeanUtils.copyProperties(user, u, new String[] { "ID", "alipay","createdatetime"
				,"invitecount", "levl" , "name" ,"phonenumber", "pwd" ,"qq", "scorefrominvite" , "userid","statu"  });
		u.setTaskcount(user.getTaskcount());			//更新任务记录
		u.setUnchangedscore(user.getUnchangedscore());	//更新可兑换积分
		u.setChangedscore(user.getChangedscore());		//更新已兑换积分
		u.setChangedcount(user.getChangedcount());		//更新兑换次数
		u.setTotalscore(user.getTotalscore());			//更新总积分
		u.setModifydatetime(new Date());				//更新操作时间
		
	}

	
	public void editinvitescore(User user) throws Exception {
		Tuser u = userDao.get(Tuser.class, user.getId());
		BeanUtils.copyProperties(user, u, new String[] { "ID", "alipay","changedcount", "changedscore","createdatetime"
				, "levl" , "name" ,"phonenumber", "pwd" ,"qq" , "userid","statu"  });
		u.setTaskcount(user.getTaskcount());			//更新任务记录
		u.setInvitecount(user.getInvitecount());		//邀请次数
		u.setScorefrominvite(user.getScorefrominvite());//邀请次数积分
		u.setUnchangedscore(user.getUnchangedscore());	//更新可兑换积分
		u.setTotalscore(user.getTotalscore());			//更新总积分
		u.setModifydatetime(new Date());				//更新操作时间
		
	}

	
	public void editlevl(User user) throws Exception {
		Tuser u = userDao.get(Tuser.class, user.getId());
		BeanUtils.copyProperties(user, u, new String[] { "ID", "alipay","changedcount", "changedscore","createdatetime","invitecount", "taskcount" , "name" ,"phonenumber", "pwd" ,"qq", "scorefrominvite" ,"totalscore", "unchangedscore", "userid","statu"  });
		u.setLevl(user.getLevl());			//更新级数
		u.setModifydatetime(new Date());	//更新操作时间
	}

	
	public void editrockscore(User user) {
		Tuser u = userDao.get(Tuser.class, user.getId());
		BeanUtils.copyProperties(user, u, new String[] { "ID", "alipay","changedcount", "changedscore","createdatetime"
				,"invitecount", "levl" , "name" ,"phonenumber", "pwd" ,"qq", "scorefrominvite" , "userid","statu"  });
		u.setTaskcount(user.getTaskcount());			//更新任务记录
		u.setTotalscore(user.getTotalscore());			//更新总积分
		u.setUnchangedscore(user.getUnchangedscore());	//更新可兑换积分
		u.setModifydatetime(new Date());	
	}
	
	
	public void updateGglCount(String userid,long ggjnunber){

		String hql="update Tuser t set t.ggjnunber = "+ggjnunber+" where t.userid= "+userid;
		userDao.executeHql(hql);
		
	}
	
	public Tuser getGglCount(String userid){
	String hql="from Tuser t  where t.userid = "+userid;
	 List<Tuser> list=userDao.find(hql);
	 if(list.size()>0){
		return  list.get(0);
	 }
		return null;
	}
	
	public void editadmin(User user) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", user.getId());
		params.put("name", user.getName());
		if (userDao.count("select count(*) from Tuser t where t.name = :name and t.id != :id", params) > 0) {
			throw new Exception("登录名已存在！");
		} else {
			Tuser u = userDao.get(Tuser.class, user.getId());
			BeanUtils.copyProperties(user, u, new String[] {"createdatetime",
					"modifydatetime",
					"taskcount",
					"changedcount",
					"invitecount",
					"scorefrominvite",
					"levl",
					"changedscore",
					"id","statu","userid"});
		}
		
	}


	public void editstatu(User user) throws Exception {
		Tuser u = userDao.get(Tuser.class, user.getId());
		BeanUtils.copyProperties(user, u, new String[] {
				"id",
				"userid",
				"createdatetime",
				"modifydatetime",
				"name",
				"pwd",
				"totalscore",
				"changedscore",
				"unchangedscore",
				"taskcount",
				"changedcount",
				"invitecount",
				"scorefrominvite",
				"phonenumber",
				"qq",
				"alipay",
				"levl"
		});
	} 
	
	public boolean jugeAcount(User user) throws Exception {
		 String hql ="";
		 String exits="";
		 if(user.getQq()== null && user.getAlipay()== null && user.getPhonenumber()==null){
			  hql=" from Tuser t  where t.userid != "+user.getUserid() ;
		 }else{
			  hql=" from Tuser t where t.userid != "+user.getUserid() ;
		 }
		 exits+="(";
		 if(user.getQq()!= null && !"".equals(user.getQq())){
			 exits+="   t.qq = '"+user.getQq()+"' or ";
		 }
		 if(user.getAlipay()!= null && !"".equals(user.getAlipay())){
			 exits+="   t.alipay = '"+user.getAlipay()+"' or ";
		 }
		 if(user.getPhonenumber()!=null && !"".equals(user.getPhonenumber())){
			 exits+="   t.phonenumber = '"+user.getPhonenumber()+"' or "; 
		 }  
		 exits = exits.substring(0, exits.lastIndexOf("or")); 
		 exits+=")";
		 if(user.getQq()== null && user.getAlipay()== null && user.getPhonenumber()==null){
			 
		 }else{
			 hql+= " and "+exits; 
		 } 
		 System.out.println(hql+"MMM");
		 List<Tuser> users=userDao.find(hql);
		 if(users.size()>0){
			  return true;
		 }else{
			  return false;
		 }
		
	}
}
